package com.qkm.xinguan.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qkm.xinguan.domain.entity.Complaint;
import com.qkm.xinguan.domain.entity.HouseInfo;
import com.qkm.xinguan.domain.infrastructure.mapper.HouseInfoMapper;
import com.qkm.xinguan.domain.infrastructure.security.LoginUser;
import com.qkm.xinguan.domain.infrastructure.utils.UserUtil;
import com.qkm.xinguan.domain.transform.dto.HouseInfoDTO;
import com.qkm.xinguan.domain.transform.error.HouseErrorInfo;
import com.qkm.xinguan.domain.transform.form.HouseInfoSearchForm;
import com.qkm.xinguan.exception.BusinessException;
import com.qkm.xinguan.repository.HouseInfoRepository;
import com.qkm.xinguan.repository.UserRepository;
import com.qkm.xinguan.response.Result;
import com.qkm.xinguan.response.ResultCode;
import com.qkm.xinguan.vo.HouseInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


@Service("houseInfoService")
public class HouseInfoRepositoryImpl extends ServiceImpl<HouseInfoMapper, HouseInfo> implements HouseInfoRepository {

	private final UserRepository userRepository;

	private final HouseInfoESService houseInfoEsService;

	@Autowired
	public HouseInfoRepositoryImpl(UserRepository userRepository, HouseInfoESService houseInfoEsService) {
		this.userRepository = userRepository;
		this.houseInfoEsService = houseInfoEsService;
	}

	/**
	 * 分页获取房屋信息列表
	 *
	 * @param page 页数
	 * @param size 条数
	 * @return Page<Notice>
	 */
	@Override
	public Page<HouseInfoVo> getHouseInfoListPage(Integer page, Integer size) {
		LambdaQueryWrapper<HouseInfo> wrapper=new LambdaQueryWrapper <>();
		wrapper.ne(HouseInfo::getVerifyState,1);
		wrapper.eq(HouseInfo::getState,0);
		Page<HouseInfo> p= this.baseMapper.selectPage(new Page<>(page, size), wrapper);
		return toHouseInfoVoPage(p);
	}

	/**
	 * 条件查询房屋列表，并且分页
	 *
	 * @param houseInfoSearchForm 查询框
	 * @param page                页码
	 * @param size                数量
	 * @return Page<HouseInfoVo>
	 */
	@Override
	public Page<HouseInfoVo> searchHouseInfoListPage(HouseInfoSearchForm houseInfoSearchForm, Integer page, Integer size) {
		LambdaQueryWrapper<HouseInfo> wrapper = executeWrapper(houseInfoSearchForm);
		Page<HouseInfo> pageInfo = this.baseMapper.selectPage(new Page<>(page, size), wrapper);
		return toHouseInfoVoPage(pageInfo);
	}

	/**
	 * @param id
	 * @param houseInfoDTO
	 * @return
	 */
	@Override
	public Result update(Long id, HouseInfoDTO houseInfoDTO) throws IOException {
		HouseInfo houseInfo=this.baseMapper.selectById(id);
		if(Objects.isNull(houseInfo)){
			throw new BusinessException(ResultCode.PARAM_ERROR, "来源信息不存在，请重试！");
		}
		houseInfo.setVerifyState(2);
		BeanUtils.copyProperties(houseInfoDTO,houseInfo);
		houseInfoEsService.editES(id,houseInfoDTO);
		int res=this.baseMapper.updateById(houseInfo);
		if(res>0){
			return Result.ok();
		}
		throw new BusinessException(ResultCode.FAILED);
	}

	/**
	 * 根据房屋id设置审核通过
	 *
	 * @param id 房屋id
	 */
	@Override
	public int updateHouseInfoStatusToPassById(Long id) {
		return this.baseMapper.updateHouseInfoStatusToPassById(id);
	}

	/**
	 * 根据房屋id设置审核不通过
	 *
	 * @param id 房屋id
	 */
	@Override
	public int updateHouseInfoStatusToFailById(Long id, HouseErrorInfo errorInfo) {
		HouseInfo houseInfo=this.baseMapper.selectById(id);
		if(Objects.isNull(houseInfo)){
			throw new BusinessException(ResultCode.PARAM_ERROR, "来源信息不存在，请重试！");
		}
		houseInfo.setErrorInfo(errorInfo.getErrorInfo());
		BeanUtils.copyProperties(errorInfo,houseInfo);
		int res=this.baseMapper.updateById(houseInfo);
		if(res>0){
			return this.baseMapper.updateHouseInfoStatusToFailById(id);
		}
		throw new BusinessException(ResultCode.FAILED);
	}

	@Override
	public HouseInfo getOnlyById(Long id) {
		return this.baseMapper.getOnlyById(id);
	}

	/**
	 * 根据userID返回对应的房屋信息
	 *
	 * @param houseInfoVoPage
	 * @return
	 */
	@Override
	public Page<HouseInfo> selectHouseInfoByUserId(Page<HouseInfo> houseInfoVoPage) {
		LambdaQueryWrapper <HouseInfo> wrapper=new LambdaQueryWrapper <>();
		LoginUser loginUser = UserUtil.getCurrentLoginUser();
		assert loginUser != null;
		if (null !=loginUser.getId()) {
			wrapper.eq(HouseInfo::getUserId, loginUser.getId());
		}
		return this.baseMapper.selectPage(houseInfoVoPage,wrapper);
	}

	@Override
	public List<HouseInfo> randomFour() {
		return this.baseMapper.randomFour();
	}

	@Override
	public int leaseHouseInfoById(Long id) {
		return this.baseMapper.leaseHouseInfoById(id);
	}


	private Page<HouseInfoVo> toHouseInfoVoPage(Page<HouseInfo> houseInfoPage) {
		Page<HouseInfoVo> pageInfo = new Page<>();
		BeanUtils.copyProperties(houseInfoPage, pageInfo);
		List<HouseInfoVo> houseInfoVos = toHouseInfoVoList(houseInfoPage.getRecords());
		pageInfo.setRecords(houseInfoVos);
		return pageInfo;
	}

	private List<HouseInfoVo> toHouseInfoVoList(List<HouseInfo> houseInfos) {
		if (houseInfos.isEmpty()) {
			return Collections.emptyList();
		}
		List<HouseInfoVo> houseInfoVos = new ArrayList<>();
		List<Long> userIds = houseInfos.stream().map(HouseInfo::getUserId).collect(Collectors.toList());
		// 根据 部门id列表查询出对应的部门名称
		List<String> userNames = userRepository.getUserNamesByIds(userIds);
		AtomicInteger index = new AtomicInteger();
		houseInfos.forEach(houseInfo -> {
			HouseInfoVo houseInfoVo = executeVo(houseInfo, userNames.get(index.getAndIncrement()));
			houseInfoVos.add(houseInfoVo);
		});
		return houseInfoVos;
	}
	private static LambdaQueryWrapper<HouseInfo> executeWrapper(HouseInfoSearchForm houseInfoSearchForm) {
		LambdaQueryWrapper<HouseInfo> wrapper = new LambdaQueryWrapper<>();
		if (null != houseInfoSearchForm.getLeaseTerm()) {
			wrapper.eq(HouseInfo::getLeaseTerm, houseInfoSearchForm.getLeaseTerm());
		}
		if (null !=houseInfoSearchForm.getState()) {
			wrapper.eq(HouseInfo::getState, houseInfoSearchForm.getState());
		}
		if (null !=houseInfoSearchForm.getDecorateState()) {
			wrapper.eq(HouseInfo::getDecorateState, houseInfoSearchForm.getDecorateState());
		}
		if (null !=houseInfoSearchForm.getHouseType()) {
			wrapper.eq(HouseInfo::getHouseType, houseInfoSearchForm.getHouseType());
		}
		LoginUser loginUser = UserUtil.getCurrentLoginUser();
		assert loginUser != null;
		wrapper.eq(HouseInfo::getUserId,loginUser.getId());
		return wrapper;
	}
	/**
	 * 构建 HouseInfoVo 对象
	 *
	 * @param houseInfo 房屋信息 Entity
	 * @param userName
	 * @return houseinfoVo
	 */
	public static HouseInfoVo executeVo(HouseInfo houseInfo, String userName) {
		HouseInfoVo houseInfoVo = new HouseInfoVo();
		BeanUtils.copyProperties(houseInfo, houseInfoVo);
		houseInfoVo.setUserName(userName);
		return houseInfoVo;
	}
}
